package com.xwn.customer.controller;

import com.xwn.api.service.IUserApi;
import com.xwn.bean.entity.User;
import com.xwn.bean.enumBean.ResultEnum;
import com.xwn.bean.exception.BodyException;
import com.xwn.bean.system.ResponseBodyEntity;
import com.xwn.bean.vo.UserVo;
import com.xwn.utils.utils.JWTUtil;
import com.xwn.utils.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author duandw
 * @Date 2019/11/19 16:12
 **/
@RestController
@Slf4j
public class UserController {

    @Autowired
    private IUserApi userApi;

    /**
     * 用户登录
     * @Param user 封装的用户对象
     * @return 返回统一格式
     **/
    @RequestMapping(value = "login" ,method = RequestMethod.POST)
    public ResponseBodyEntity login(@RequestBody User user){
        ResponseBodyEntity response = new ResponseBodyEntity();

        if (user.getPassword() == null || "".equals(user.getPassword())) {
            throw new BodyException(ResultEnum.LOGIN_NULL_PASS);
        }

        //判断是否存在该用户
        User u = userApi.findUserByName(user.getUsername());
        if (u == null) {
            throw new BodyException(ResultEnum.LOGIN_NO_ACCOUNT);
        }

        //判断密码
        try {
            if (!MD5Util.verify(user.getPassword(),u.getPassword())) {
                throw new BodyException(ResultEnum.LOGIN_FAIL_PASS);
            }
        } catch (Exception e) {
            log.error("MD5执行异常");
            throw new BodyException(ResultEnum.LOGIN_FAIL_PASS);
        }

        //更新登录状态
        UserVo vo = new UserVo();
        try {
            vo.setToken(JWTUtil.createToken(u.getUsername()));
            vo.setUser(userApi.updateUser(u));
        } catch (Exception e) {
            throw new BodyException(ResultEnum.LOGIN_FAITRUE);
        }

        response.setCode(200);
        response.setData(vo);
        response.setMsg("登录成功");
        return response;
    }
}
